package com.dmwork.service.interaction.controller.front.me;

import com.dmwork.common.base.result.R;
import com.dmwork.common.base.util.JwtInfo;
import com.dmwork.common.base.util.JwtUtils;
import com.dmwork.service.interaction.entity.vo.CommentMessageVo;
import com.dmwork.service.interaction.feign.MessageFeignService;
import com.dmwork.service.interaction.mq.sender.MessageSender;
import com.dmwork.service.interaction.service.FeedCommentService;
import com.dmwork.service.interaction.service.WorkCommentService;
import com.google.gson.Gson;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.ApiOperation;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Transactional
@RestController
@RequestMapping("/front/dm_work/interaction/comment_message_info/me")
public class FrontMeCommentMessageInfoController {

    @Autowired
    private WorkCommentService workCommentService;
    @Autowired
    private FeedCommentService feedCommentService;
    @Autowired
    private MessageFeignService messageFeignService;
    @Autowired
    private MessageSender messageSender;

    @ApiOperation("获取评论消息")
    @GetMapping("get_comment_message_info_list/{page}/{limit}")
    public R getCommentMessageInfoList(HttpServletRequest request, @PathVariable Integer page, @PathVariable Integer limit) {
        JwtInfo jwtInfo = JwtUtils.getCustomerInfoByJwtToken(request);
        R commentMessageListResult = messageFeignService.getCommentMessageList(page, limit);
        if (!commentMessageListResult.getSuccess()) {
            return R.error().message("获取失败");
        }
        int total = (int) commentMessageListResult.getData().get("total");
        if (total == 0) {
            return R.ok().message("暂无数据").data("total", 0);
        }

        JSONArray commentMessageListJsonArray = new JSONArray(new Gson().toJson(commentMessageListResult.getData().get("rows")));
        List<String> workCommentIdList = new ArrayList<>(); //作品部分评论id列表
        List<String> feedCommentIdList = new ArrayList<>(); //动态部分评论id列表
        List<CommentMessageVo> commentMessageVoList = new ArrayList<>();
        int unreadCount = 0;
        for (int i = 0; i < commentMessageListJsonArray.length(); i++) {
            JSONObject commentMessageJsonObject = commentMessageListJsonArray.getJSONObject(i);
            if (commentMessageJsonObject.getInt("type") == 0) {
                workCommentIdList.add(commentMessageJsonObject.getString("commentId"));
            } else if (commentMessageJsonObject.getInt("type") == 1) {
                feedCommentIdList.add(commentMessageJsonObject.getString("commentId"));
            }
            //统计未读消息数量
            int readStatus = commentMessageJsonObject.getInt("readStatus");
            if (readStatus == 0) {
                unreadCount++;
            }
        }
        if (workCommentIdList.size() > 0) {
            commentMessageVoList.addAll(workCommentService.getCommentMessageList(workCommentIdList));
        }
        if (feedCommentIdList.size() > 0) {
            commentMessageVoList.addAll(feedCommentService.getCommentMessageList(feedCommentIdList));
        }
        //按照时间降序排序
        Collections.sort(commentMessageVoList, new Comparator<CommentMessageVo>() {
            @Override
            public int compare(CommentMessageVo o1, CommentMessageVo o2) {
                boolean before = o1.getGmtCreate().before(o2.getGmtCreate());
                if (before) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });

        for (CommentMessageVo commentMessageVo : commentMessageVoList) {
            //转换Emoji
            if (!StringUtils.isEmpty(commentMessageVo.getComment())) {
                commentMessageVo.setComment(EmojiParser.parseToUnicode(commentMessageVo.getComment()));
            }
            //设置消息已读状态
            for (int i = 0; i < commentMessageListJsonArray.length(); i++) {
                JSONObject jsonObject = commentMessageListJsonArray.getJSONObject(i);
                if (commentMessageVo.getCommentId().equals(jsonObject.getString("commentId"))) {
                    commentMessageVo.setReadStatus(jsonObject.getInt("readStatus"));
                    break;
                }
            }
        }

        // 若未读消息数量大于0，则向MQ发送评论消息已读的消息，让消息系统将未读的评论消息设置为已读
        if (unreadCount > 0) {
            messageSender.sendCommentReadMessage(jwtInfo.getId(), new HashMap<>());
        }

        return R.ok().data("total", total).data("rows", commentMessageVoList);
    }

}
